﻿#include "Book_Ticket_Show_Window.h"
#include <Global_Class.h>
#include <QMessageBox>
#include <QPushButton>
#include <QComboBox>
#include <QLabel>
#include <orders.h>
#include <seats.h>
#include <algorithm>
#include <Constants.h>
using namespace Constants;

// 辅助函数：获取某车次某站点的stopOrder
int getStopOrder(int trainId, int stationId) {
    for (const auto& sch : allData->trainSchedules) {
        if (sch.getTrainId() == trainId && sch.getStationId() == stationId) {
            return sch.getStopOrder();
        }
    }
    return -1;
}

Book_Ticket_Show_Window::Book_Ticket_Show_Window(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	setupWindow();
	loadAvailableSeats();
	connect(ui.btn_autoAssign, &QPushButton::clicked, this, &Book_Ticket_Show_Window::on_btn_autoAssign_clicked);
	connect(ui.comboBox_seat, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Book_Ticket_Show_Window::on_comboBox_seat_currentIndexChanged);
	connect(ui.btn_submit, &QPushButton::clicked, this, &Book_Ticket_Show_Window::on_btn_submit_clicked);
}

Book_Ticket_Show_Window::~Book_Ticket_Show_Window() {}

// 移除静态变量，改为成员变量

void Book_Ticket_Show_Window::setupWindow()
{
    ui.value_trainCode->setText(QString::fromStdString(bookTicket->getTrainCode()));
    ui.value_startStation->setText(QString::fromStdString(bookTicket->getStartStation()));
    ui.value_endStation->setText(QString::fromStdString(bookTicket->getEndStation()));
    ui.value_departTime->setText(QString::fromStdString(bookTicket->getDepartTime()));
    ui.value_arriveTime->setText(QString::fromStdString(bookTicket->getArriveTime()));
    // 票价显示
    int startStationId = -1, endStationId = -1;
    for (const auto& station : allData->stationsQueue) {
        if (station.getName() == bookTicket->getStartStation()) startStationId = station.getStationId();
        if (station.getName() == bookTicket->getEndStation()) endStationId = station.getStationId();
    }
    double priceBusiness = AllData::CalculateTicketPrice(startStationId, endStationId, "商务座", allData->stationsQueue);
    double priceFirst = AllData::CalculateTicketPrice(startStationId, endStationId, "一等座", allData->stationsQueue);
    double priceSecond = AllData::CalculateTicketPrice(startStationId, endStationId, "二等座", allData->stationsQueue);
    ui.value_price->setText(QString("商务座: %1元  一等座: %2元  二等座: %3元")
        .arg(priceBusiness < 0 ? "-" : QString::number(priceBusiness, 'f', 2))
        .arg(priceFirst < 0 ? "-" : QString::number(priceFirst, 'f', 2))
        .arg(priceSecond < 0 ? "-" : QString::number(priceSecond, 'f', 2)));
    // 修复：显示正确的乘车日期
    ui.value_date->setText(QString::fromStdString(bookTicket->getTravelDate()));
}

void Book_Ticket_Show_Window::loadAvailableSeats()
{
    availableSeats.clear();
    ui.comboBox_seat->clear();
    int trainId = -1;
    for (const auto& train : allData->trainQueue) {
        if (train.getTrainCode() == bookTicket->getTrainCode()) {
            trainId = train.getTrainId();
            break;
        }
    }
    if (trainId == -1) return;
    for (const auto& seat : allData->seatsQueue) {
        if (seat.getTrainId() == trainId) {
            if (isSeatAvailable(seat.getSeatNo())) {
                availableSeats.push_back(seat.getSeatNo());
                ui.comboBox_seat->addItem(QString::fromStdString(seat.getSeatNo()));
            }
        }
    }
    if (!availableSeats.empty()) {
        selectedSeatNo = availableSeats[0];
        ui.value_selectedSeat->setText(QString::fromStdString(selectedSeatNo));
    } else {
        selectedSeatNo = "";
        ui.value_selectedSeat->setText("无可用座位");
    }
}

bool Book_Ticket_Show_Window::isSeatAvailable(const std::string& seatNo)
{
    int trainId = -1;
    for (const auto& train : allData->trainQueue) {
        if (train.getTrainCode() == bookTicket->getTrainCode()) {
            trainId = train.getTrainId();
            break;
        }
    }
    if (trainId == -1) return false;
    int startStationId = -1, endStationId = -1;
    for (const auto& station : allData->stationsQueue) {
        if (station.getName() == bookTicket->getStartStation()) startStationId = station.getStationId();
        if (station.getName() == bookTicket->getEndStation()) endStationId = station.getStationId();
    }
    std::string date = ui.value_date ? ui.value_date->text().toStdString() : "";
    if (date.empty()) date = QDate::currentDate().toString("yyyy-MM-dd").toStdString();
    int seatId = -1;
    for (const auto& seat : allData->seatsQueue) {
        if (seat.getTrainId() == trainId && seat.getSeatNo() == seatNo) {
            seatId = seat.getSeatId();
            break;
        }
    }
    if (seatId == -1) return false;
    // 使用seatOccupy机制判断区间可用
    return allData->IsSeatAvailable(date, trainId, seatId, startStationId, endStationId);
}

void Book_Ticket_Show_Window::on_btn_autoAssign_clicked()
{
	if (availableSeats.empty()) {
		QMessageBox::warning(this, "无可用座位", "没有可用座位可分配！");
		return;
	}
	bool found = false;
	for (size_t i = 0; i < availableSeats.size(); ++i) {
		if (isSeatAvailable(availableSeats[i])) {
			selectedSeatNo = availableSeats[i];
			ui.comboBox_seat->setCurrentIndex(static_cast<int>(i));
			ui.value_selectedSeat->setText(QString::fromStdString(selectedSeatNo));
			found = true;
			break;
		}
	}
	if (!found) {
		selectedSeatNo = "";
		ui.value_selectedSeat->setText("无可用座位");
		QMessageBox::warning(this, "无可用座位", "没有可用座位可分配！");
	}
}

void Book_Ticket_Show_Window::on_comboBox_seat_currentIndexChanged(int idx)
{
	if (idx >= 0 && idx < (int)availableSeats.size()) {
		selectedSeatNo = availableSeats[idx];
		ui.value_selectedSeat->setText(QString::fromStdString(selectedSeatNo));
	}
}

void Book_Ticket_Show_Window::on_btn_submit_clicked()
{
    if (hasSubmitted) return;
    hasSubmitted = true;
    if (selectedSeatNo.empty()) {
        QMessageBox::warning(this, "购票失败", "请选择座位！");
        hasSubmitted = false;
        return;
    }
    int seatId = -1, trainId = -1;
    std::string seatTypeStr = "";
    for (const auto& train : allData->trainQueue) {
        if (train.getTrainCode() == bookTicket->getTrainCode()) {
            trainId = train.getTrainId();
            break;
        }
    }
    // 必须先查到seatTypeStr
    for (auto& seat : allData->seatsQueue) {
        if (seat.getTrainId() == trainId && seat.getSeatNo() == selectedSeatNo) {
            seatId = seat.getSeatId();
            // 查找座型,通过SeatNo获取座型，SeatNo的第一个数字决定座型，1表示商务座，2表示一等座，3表示二等座
            char seatTypeChar = selectedSeatNo[0];
            if (seatTypeChar == '1') seatTypeStr = "商务座";
            else if (seatTypeChar == '2') seatTypeStr = "一等座";
            else if (seatTypeChar == '3') seatTypeStr = "二等座";
            seat.setStatus(1); // 占用座位
            break;
        }
    }
    if (seatId == -1 || seatTypeStr.empty()) {
        QMessageBox::warning(this, "购票失败", "座位信息有误或座型缺失！");
        hasSubmitted = false;
        return;
    }
    int startStationId = -1, endStationId = -1;
    for (const auto& station : allData->stationsQueue) {
        if (station.getName() == bookTicket->getStartStation()) startStationId = station.getStationId();
        if (station.getName() == bookTicket->getEndStation()) endStationId = station.getStationId();
    }
    int startOrder = getStopOrder(trainId, startStationId);
    int endOrder = getStopOrder(trainId, endStationId);
    if (startOrder == -1 || endOrder == -1) {
        QMessageBox::warning(this, "购票失败", "站点信息有误！");
        hasSubmitted = false;
        return;
    }
    std::string date = ui.value_date ? ui.value_date->text().toStdString() : "";
    if (date.empty()) date = QDate::currentDate().toString("yyyy-MM-dd").toStdString();
    for (const auto& order : allData->ordersQueue) {
        if (order.getTrainId() == trainId && order.getTravelDate() == date && order.getSeatId() == seatId && order.getStatus() == order.booked) {
            int oStartOrder = getStopOrder(trainId, order.getStartStationId());
            int oEndOrder = getStopOrder(trainId, order.getEndStationId());
            if (oStartOrder == -1 || oEndOrder == -1) continue;
            if (!((endOrder <= oStartOrder) || (oEndOrder <= startOrder))) {
                QMessageBox::warning(this, "购票失败", "所选座位在您的乘车区间内已被占用，请重新选择。");
                hasSubmitted = false;
                return;
            }
        }
    }
    int newOrderId = (allData->ordersQueue.empty() ? 1 : allData->ordersQueue.back().getOrderId() + 1);
    // 计算票价，直接通过所定的座型，找到对应的票价
    double price = AllData::CalculateTicketPrice(startStationId, endStationId, seatTypeStr, allData->stationsQueue);
    orders newOrder;
    newOrder.setOrderId(newOrderId);
    std::string userIdStr = userWindow->getCurrentUser().getUserId();
    int userId = 0;
    try { userId = std::stoi(userIdStr); } catch (...) { userId = 0; }
    newOrder.setUserId(userId);
    newOrder.setTrainId(trainId);
    newOrder.setSeatId(seatId);
    newOrder.setStartStationId(startStationId);
    newOrder.setEndStationId(endStationId);
    newOrder.setTravelDate(date);
    newOrder.setOrderTime(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toStdString());
    newOrder.setStatus(orders::booked);
    newOrder.setPrice(price); 
    allData->ordersQueue.push_back(newOrder);
    allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
    allData->Seat_WriteToFile(SEAT_INFORMATION_FILE_POSITION); // 保存座位状态
    // 添加座位占用记录
    SeatOccupy so(date, trainId, seatId, selectedSeatNo, startStationId, endStationId, newOrderId);
    allData->seatOccupyQueue.push_back(so);
    allData->SeatOccupy_WriteToFile("seat_occupy.txt");
    showOrderResult(true, "购票成功！", newOrderId);
    this->accept();
}

void Book_Ticket_Show_Window::showOrderResult(bool success, const QString& msg, int orderId)
{
	if (success) {
		QMessageBox::information(this, "购票成功", msg + "\n订单号: " + QString::number(orderId));
	} else {
		QMessageBox::warning(this, "购票失败", msg);
	}
}